package com.sport.facilities.booking.system.core;

import java.util.List;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.util.SimpleNodeIterator;

import com.sport.facilities.booking.system.htmlchecker.ActionMethod;

public class HtmlHelper {
	private final static String CHARSET = "UTF-8";

	public static NodeList getNodeList(String html) throws ParserException {
		Parser parser = Parser.createParser(html, CHARSET);
		NodeList list = null;
		list = parser.parse(null);
		return list;
	}

	public static void scanNodeForPatternAddToTarget(NodeList nodeList,
			List targetlist, String pattern, ActionMethod ac) {
		SimpleNodeIterator iterator = nodeList.elements();
		while (iterator.hasMoreNodes()) {
			Node node = iterator.nextNode();
			NodeList childList = node.getChildren();
			if (childList == null) {
				String result = node.getText();
				if (result.indexOf(pattern) != -1) {
					ac.addObjectToList(result, targetlist);
				}
			} else {
				scanNodeForPatternAddToTarget(nodeList, targetlist, pattern, ac);
			}
		}
	}

	public static NodeList getNodeListByTag(String html, String tag)
			throws ParserException {
		NodeList nodelist;
		Parser parser = Parser.createParser(html, CHARSET);
		NodeFilter filter = new TagNameFilter(tag);
		nodelist = parser.parse(filter);
		return nodelist;
	}

	public static NodeList getNodeListByClass(String html, Class filterClass)
			throws ParserException {
		NodeList list = null;
		Parser parser = new Parser(html);
		NodeFilter inputFilter = new NodeClassFilter(filterClass);
		list = parser.parse(inputFilter);
		return list;

	}

	public static String getInputName(String result) {
		int startIndex = result.indexOf("name=\"") + 6;
		int endIndex = result.indexOf("\"", startIndex);
		return result.substring(startIndex, endIndex);
	}

	public static String getInputValue(String result) {
		int startIndex = result.indexOf("value=\"") + 7;
		int endIndex = result.indexOf("\"", startIndex);
		return result.substring(startIndex, endIndex);
	}
}
